//
//  LS_EmoticonToolBar.swift
//  EmoticonKeyboard
//
//  Created by 罗李苏 on 16/5/30.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit

class LS_EmoticonToolBar: UIStackView {
    //定义属性记录选中的按钮
    var currentBtn: UIButton?
    //定义闭包
    var selectedIndexCallBack: ((index: Int) -> ())?

    init(){
        super.init(frame: CGRectZero)
        //设置背景色
        backgroundColor = UIColor.redColor()
        //设置轴
        axis = .Horizontal
        //设置填充样式
        distribution = .FillEqually
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        addChildButtons("默认", backImageName: "compose_emotion_table_left", index: 0)
        addChildButtons("Emoji", backImageName: "compose_emotion_table_mid",index: 1)
        addChildButtons("浪小花", backImageName: "compose_emotion_table_right", index: 2)
    
    }
    //MARK:创建子控件的方法
    private func addChildButtons(title: String, backImageName: String,index: Int){
        let btn = UIButton()
        btn.tag = index
        btn.setTitle(title, forState: .Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Selected)
        btn.setBackgroundImage(UIImage(named: backImageName + "_normal"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: backImageName + "_selected"), forState: .Selected)
        //添加点击事件
        btn.addTarget(self, action: #selector(LS_EmoticonToolBar.btnDidClick(_:)), forControlEvents: .TouchUpInside)
        //UIStackView添加子视图 不能够使用addSubview
        addArrangedSubview(btn)
        //MARK:默认选中第一个按钮
        if index == 0 {
            btn.selected = true
            currentBtn = btn
        }
        
    }
    
    //MARK:按钮的点击事件
    @objc private func btnDidClick(btn: UIButton){
        print("背靠背滴幸福")
        //取消保存的选中按钮
        currentBtn?.selected = false
        //当前按钮成为选中状态
        btn.selected = true
        //保存选中按钮
        currentBtn = btn
        
        //执行闭包完成回调
        selectedIndexCallBack!(index:btn.tag)
    }
    
}
